const db = require('./db')
const tool = require('./tools/tool')

module.exports = {
    tasks: [],
    running: false,
    async run() {
        if (this.tasks.length == 0) return
        if (this.running) return
        this.running = true
        tool.cLog.runner(1)
        // console.log('运行')
        while (1) {
            if (this.tasks.length == 0) {
                this.running = false
                tool.cLog.runner(0)
                // console.log('停止')
                break
            }
            let curr = this.tasks[0]
            try {
                tool.cLog.api(curr.exp, curr.method, curr.auth, 1, curr.data)
                await db.exe('START TRANSACTION;')
                this.currentData = curr.data
                let re = await curr.func(curr.data, curr.headers, curr.req)
                await db.exe('COMMIT;')
                curr.res.send({
                    status: 1,
                    content: 'success',
                    data: re
                })
                tool.cLog.api(curr.exp, curr.method, curr.auth, 2, curr.data)
            } catch (error) {
                console.log(error)
                await db.exe('ROLLBACK;')
                tool.cLog.api(curr.exp, curr.method, curr.auth, 0, curr.data)
                try {
                    curr.res.send({
                        status: 0,
                        content: tool.string.delete.bySubString(error.toString(), 'Error:')
                    })
                } catch (error) {

                }
            }
            this.shift()
        }
    },
    async add(func, res, headers, data, req, exp, method, auth) {
        this.tasks.push({ func, res, headers, data, req, exp, method, auth })
        this.run()
        await tool.wait(0.1)
        this.run()
    },
    shift() {
        this.tasks.shift()
    },
    currentData: {}
}